﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ext.Net;
using ZP.Data;
using ZP.Service;
using Kwan.web;
using Kwan.service;

namespace ZP.Web.Admin.Job
{
    public partial class Default : System.Web.UI.Page
    {
        BaseService<TJob, VJob, int> facade = new BaseService<TJob, VJob, int>();
        BaseService<TCity, TCity, string> facadeCity = new BaseService<TCity, TCity, string>();
        BaseService<TIndustry, TIndustry, string> facadeIndustry = new BaseService<TIndustry, TIndustry, string>();
        BaseService<TFuntype, TFuntype, string> facadeFuntype = new BaseService<TFuntype, TFuntype, string>();

        public static List<TFuntype> funList = null;
        List<TFuntype> funParentList = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                IndustryDS.DataSource = facadeIndustry.EntityDAO.Load(null);
                IndustryDS.DataBind();

                funList = facadeFuntype.EntityDAO.Load(null);
                funParentList = funList.FindAll(delegate(TFuntype tt)
                {
                    return tt.Code.Substring(2, 2) == "00";
                });
                FuntypeDS.DataSource = funParentList;
                FuntypeDS.DataBind();

                JobareaDS.DataSource = facadeCity.EntityDAO.Load(null);
                JobareaDS.DataBind();
            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            NewJob();
            ShowEditWindow();
        }

        protected void BtnDeleteInfo_Click(object sender, DirectEventArgs e)
        {
            Dictionary<string, string>[] selected = JSON.Deserialize<Dictionary<string, string>[]>(e.ExtraParams["Values"]);
            if (selected.Length <= 0)
            {
                Notification notify = ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
                return;
            }
            foreach (Dictionary<string, string> row in selected)
            {
                facade.DeleteById(row["id"]);
            }
            Store1.DataBind();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            Dictionary<string, string>[] selected = JSON.Deserialize<Dictionary<string, string>[]>(obj);
            if (selected.Length > 0)
            {
                foreach (Dictionary<string, string> s in selected)
                {
                    facade.EntityDAO.DeleteById(s["id"]);
                }
                Store1.DataBind();
            }
        }

        [DirectMethod]
        public void ChangeFuntype(string code)
        {
            DomObject Child = new DomObject();
            DomObject ul = new DomObject { Tag = HtmlTextWriterTag.Ul };
            List<TFuntype> funChild = funList.FindAll(delegate(TFuntype tt)
            {
                return tt.Code.Substring(0, 2) == code.Substring(0, 2);
            });
            foreach (TFuntype t in funChild)
            {
                ul.Children.Add(CreateCmbDom(t.Name, t.Code));
            }
            ul.Children.Add(new DomObject
            {
                Tag = HtmlTextWriterTag.A,
                Html = "关闭",
                CustomConfig = {
                    new ConfigItem("href", "#", ParameterMode.Value),
                    new ConfigItem("onClick", "Job.Close('Layer2')", ParameterMode.Value)
                }
            });
            Child.Children.Add(ul);
            Layer layer = new Layer(new LayerConfig
            {
                ID = "Layer2",
                DH = { Cls = "layer", Children = { Child } }
            });

            layer.AlignTo(CmbFuntype.Element, "tl-tr", new int[] { 5, 0 }).SlideIn("l");

        }

        [DirectMethod]
        public void DoChangeFuntype(string obj, string code)
        {
            code = CmbFuntype.Value.ToString();
            Dictionary<string, string>[] selected = JSON.Deserialize<Dictionary<string, string>[]>(obj);
            if (selected.Length > 0)
            {
                foreach (Dictionary<string, string> s in selected)
                {
                    TJob job = facade.EntityDAO.LoadById(s["id"]);
                    job.Funtype = code;
                    facade.EntityDAO.Save(job);
                }
                Store1.DataBind();
            }
            else
            {
                Notification notify = ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void ChangeState(string id, string cmd)
        {
            TJob tt = facade.EntityDAO.LoadById(id);
            switch (cmd)
            {
                case "Scale": tt.Scale = tt.Scale == "1" ? "0" : "1"; break;
            }
            tt.CreatedDate = DateTime.Now;
            facade.EntityDAO.Save(tt);
            Store1.DataBind();
        }

        [DirectMethod]
        public void ChangeAllState(string obj, string cmd)
        {
            Dictionary<string, string>[] selected = JSON.Deserialize<Dictionary<string, string>[]>(obj);
            if (selected.Length > 0)
            {
                foreach (Dictionary<string, string> s in selected)
                {
                    TJob job = facade.EntityDAO.LoadById(s["id"]);
                    string[] arr = cmd.Split(char.Parse("_"));
                    job.Scale = arr[1];
                    facade.EntityDAO.Save(job);
                }
                Store1.DataBind();
            }
            else
            {
                Notification notify = ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void EditInfo(string id)
        {
            SetEmployee(facade.EntityDAO.LoadById(id));
            ShowEditWindow();
        }

        [DirectMethod]
        public void DeleteInfo(string id)
        {
            facade.DeleteById(id);
            Store1.DataBind();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());

            ps.Set("keywordtype", "2");
            ps.Set("keyword", txtSearch.Text);
            ps.Set("funtype", searchCid.Text);

            facade.ViewDAO.QueryBuilder = new JobQuery();
            List<VJob> ListView = facade.LoadListData(ps, e.Start > 0 ? e.Start : 0, e.Limit);

            e.Total = Convert.ToInt32(facade.TotalCount(ps));


            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        protected void ShowEditWindow()
        {
            EditWindow.Show();
            //EditWindow.Collapsed = false;
        }

        protected void NewJob()
        {
            txtID.Text = string.Empty;
            txtJobName.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtEndDate.Text = DateTime.Now.AddMonths(6).ToString("yyyy-MM-dd hh:mm:ss");
            txtIssuedate.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            txtFuntype.Text = "";
            txtScale.Text = "1";
            txtJobarea.Text = "";
        }

        protected void SetEmployee(TJob job)
        {
            txtID.Text = job.id.ToString();
            txtJobName.Text = job.JobName;
            txtDescription.Text = job.Description;
            txtEndDate.Text = job.EndDate.ToString("yyyy-MM-dd hh:mm:ss");
            txtIssuedate.Text = job.Issuedate.ToString("yyyy-MM-dd hh:mm:ss");
            txtFuntype.Text = job.Funtype;
            txtScale.Text = job.Scale;
            txtJobarea.Value = job.Jobarea;
        }

        protected void SaveEmployee(object sender, DirectEventArgs e)
        {
            TJob job = !String.IsNullOrEmpty(txtID.Text) ? facade.EntityDAO.LoadById(txtID.Text) : new TJob();

            job.JobName = txtJobName.Text;
            job.Funtype = txtFuntype.Text;
            job.Description = txtDescription.Text;
            job.EndDate = DateTime.Parse(DateTime.Now.AddMonths(6).ToString("yyyy-MM-dd hh:mm:ss"));
            job.Issuedate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            job.Scale = txtScale.Value.ToString();
            job.Jobarea = txtJobarea.Value.ToString();

            facade.EntityDAO.Save(job);

            Store1.DataBind();
            EditWindow.Hide();
        }

        [DirectMethod]
        public void ShowFuntype(string code, string eID)
        {
            DomObject Child = new DomObject();
            DomObject ul = new DomObject { Tag = HtmlTextWriterTag.Ul };
            List<TFuntype> funChild = funList.FindAll(delegate(TFuntype tt) {
                return tt.Code.Substring(0, 2) == code.Substring(0, 2);
            });
            foreach (TFuntype t in funChild)
            {
                ul.Children.Add(CreateDom(t.Name, t.Code, eID));
            }
            ul.Children.Add(new DomObject
            {
                Tag = HtmlTextWriterTag.A,
                Html = "关闭",
                CustomConfig = {
                    new ConfigItem("href", "#", ParameterMode.Value),
                    new ConfigItem("onClick", "Job.Close('Layer1')", ParameterMode.Value)
                }
            });
            Child.Children.Add(ul);
            Layer layer = new Layer(new LayerConfig
            {
                ID = "Layer1",
                DH ={ Cls = "layer", Children = { Child } }
            });
            layer.AlignTo(X.Get(eID), "tl-tr", new int[] { 5, 0 }).SlideIn("l");
        }

        private DomObject CreateDom(string text, string value,string eID)
        {
            DomObject li = new DomObject { Tag = HtmlTextWriterTag.Li };
            DomObject dom = new DomObject
            {
                Tag = HtmlTextWriterTag.A,
                Html = text,
                CustomConfig = {
                    new ConfigItem("href", "#", ParameterMode.Value),
                    new ConfigItem("onClick", "#{"+eID+"}.insertItem(0, '"+text+"', '"+value+"');#{"+eID+"}.setValue('"+value+"');Job.Close('Layer1')", ParameterMode.Value)
                }
            };
            li.Children.Add(dom);
            return li;
        }

        private DomObject CreateCmbDom(string text, string value)
        {
            DomObject li = new DomObject { Tag = HtmlTextWriterTag.Li };
            DomObject dom = new DomObject
            {
                Tag = HtmlTextWriterTag.A,
                Html = text,
                CustomConfig = {
                    new ConfigItem("href", "#", ParameterMode.Value),
                    new ConfigItem("onClick", "Job.DoChangeFuntype(Ext.encode(#{GridPanel1}.getRowsValues({selectedOnly:true})),"+value+");Job.Close('Layer2')", ParameterMode.Value)
                }
            };
            li.Children.Add(dom);
            return li;
        }

        [DirectMethod]
        public void Close(string id)
        {
            X.Get(id).SlideOut("l", new FxConfig
            {
                Callback = new JFunction(X.Get(id).ChainOn().Remove().ToScript())
            });
        }
    }
}